import { constantRoutes } from '@/router/index'
import { getRouters } from '@/api/menu'
// import Layout from '@/views/layout/Layout'
import { filterAsyncRouter } from '@/utils/router'
import { find, get,reduce } from 'lodash'
import { handleMicroApps } from "@/utils/router";
// import { dynamicRoutes } from "@/utils/permission";
const permission = {
  state: {
    routes: [],
    addRoutes: [],
    routesName:'',
    microApps:[],
    microMenu:[]
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    },
    SET_ROUTES_NAME: (state, name) => {
      state.routesName = name
    },
    SET_MICRO_MENU: (state, menu) => {
      state.microMenu = menu;
    },
    SET_MICRO_APPS: (state, microApps) => {
      const asyncRoutes = handleMicroApps(microApps);
      state.microApps = reduce(
        asyncRoutes,
        (apps, { path, ip }) => {

          if (ip) {
            //自动添加上域名
            if (ip.startsWith("/")) {
              ip = window.location.host + ip;
            }
      
            const microApp = {
              name: path,
              entry: `//${ip}/`,
              container: "#micro",
              activeRule: "/" + path,
            };
            // apps.push(microApp);
          }
          return apps;
        },
        []
      );
    },
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        getRouters().then(res => {
          const routes = get(find(get(res, 'data.data'), { path: "system-management/systemmanagement" }), 'children', [])
          const accessedRoutes = filterAsyncRouter(routes)
          commit('SET_ROUTES', accessedRoutes)
          commit('SET_MICRO_APPS', accessedRoutes)
          console.log(routes,'生成路由');
          resolve(accessedRoutes);
        })
      })
    }
  }
}

export default permission